import os
import time

# 日志文件所在的目录
# 计费日志_接口调用次数：/opt/billinglog
# 调用日志：/opt/log
LOG_DIRS = ('/opt/billinglog', '/opt/log')

# 保留日志的天数，例如保留30天内的日志
DAYS_TO_KEEP = 30

# 转换天数为秒数
SECONDS_TO_KEEP = DAYS_TO_KEEP * 24 * 60 * 60


def delete_old_logs():
    """删除旧日志文件"""
    current_time = time.time()

    for dir_path in LOG_DIRS:
        for root, dirs, files in os.walk(dir_path):
            level = root.replace(dir_path, '').count(os.sep)
            indent = ' ' * 4 * (level)
            for fileName in files:
                print(root + '/' + fileName)
                if fileName.endswith('.log.gz'):
                    file_path = os.path.join(root, fileName)
                    # 检查文件是否为文件且修改时间早于当前时间减去保留天数
                    if os.path.isfile(file_path) and os.path.getmtime(file_path) < current_time - SECONDS_TO_KEEP:
                        print("Deleting old log file: " + file_path)
                        os.remove(file_path)


delete_old_logs()
